﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using VirtualHost.Models;

namespace VirtualHost.Services {
    public class HostService {
        public SysSettimgs Settimgs { get; private set; }
        public const String App = "nginx.exe";
        public const String FILE_SETTINGS = "settings.json";

        public HostService() {
            LoadSettings();
        }


        #region 1.0 启动Nginx服务 +void Start() 
        /// <summary>
        /// 启动Nginx服务
        /// </summary>
        public void Start() {
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(Settimgs.NginxPath + App);
            process.StartInfo.WorkingDirectory = Settimgs.NginxPath;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
        }
        #endregion

        #region 2.0 停止Nginx服务 +int Stop() 
        /// <summary>
        /// 停止Nginx服务
        /// </summary>
        /// <returns></returns>
        public int Stop() {
            Process[] list = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(App));
            foreach (Process item in list) {
                item.Kill();
            }
            return list.Length;
        }
        #endregion

        #region 3.0 检查服务是否启动 + Boolean IsRuning()
        /// <summary>
        /// 检查服务是否启动
        /// </summary>
        /// <returns></returns>
        public Boolean IsRuning() {
            Process[] list = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(App));
            return list.Length > 0;
        }
        #endregion

        #region 4.0 加载配置文件 +void LoadSettings() 
        /// <summary>
        /// 加载配置文件
        /// </summary>
        public void LoadSettings() {
            try {
                if (!File.Exists(FILE_SETTINGS)) {
                    Settimgs = new SysSettimgs();
                    return;
                }

                String contents = File.ReadAllText(FILE_SETTINGS);
                Settimgs = JsonConvert.DeserializeObject<SysSettimgs>(contents);


            } catch (Exception ex) {

                Console.WriteLine(ex.Message);
            }
        }
        #endregion

        #region 5.0 保存配置文件 +void SaveSettings() 
        /// <summary>
        /// 保存配置文件
        /// </summary>
        public void SaveSettings() {
            try {
                String contents = JsonConvert.SerializeObject(Settimgs);
                File.WriteAllText(FILE_SETTINGS, contents);

            } catch (Exception ex) {

                Console.WriteLine(ex.Message);
            }
        }
        #endregion

    }
}
